﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using TeamTime.Classes;
using StillVoiceCommon;

namespace TeamTime
{
    public partial class PersonFormControl : System.Web.UI.UserControl
    {
        public string SaveButtonText { get { return this.btnSave.Text; } set { this.btnSave.Text = value; } }


        public bool SaveButtonVisible { get; set; }
        private bool liteMode;
        public bool LiteMode
        {
            get { return liteMode; }
            set
            {
                liteMode = value;
                //trCompany.Visible = !liteMode;
                trDepartment.Visible = !liteMode;
                trDietaryRequirements.Visible = !liteMode;
                trOffice.Visible = !liteMode;
                trDepartment.Visible = !liteMode;
                trPosition.Visible = !liteMode;
                
            }
        }
        public bool EndUserMode
        {
            get
            {
                if (this.Attributes["EndUserMode"] == null)
                {
                    User user = new User(); user.load(Convert.ToInt32(Session["UserID"]));
                    this.Attributes.Add("EndUserMode", user.isEndUser().ToString());
                }
                return (this.Attributes["EndUserMode"].ToString() == true.ToString());
            }
            set
            {
                this.Attributes.Add("EndUserMode", value.ToString());
            }
        }
        private bool hideSaveButton;
        public bool HideSaveButton
        {
            get { return hideSaveButton; }
            set
            {
                hideSaveButton = value;
                trSaveButton.Visible = !hideSaveButton;
                trModif.Visible = !hideSaveButton;
            }
        }

        public bool SuccessfullySaved
        {
            get { return this.chkSuccessfullySaved.Checked; }
            set { this.chkSuccessfullySaved.Checked = value; }
        }
        public Int32 LatestCompanyPersonID
        {
            get
            {
                if (this.txtCompanyID.Text == "") this.txtCompanyID.Text = "0";
                return Convert.ToInt32(this.Attributes["LatestCompanyPersonID"]);
            }
            set
            {
                Attributes.Add("LatestCompanyPersonID", value.ToString());
            }
        }

        public Int32 PersonID
        {
            get { return Convert.ToInt32(this.txtID.Text); }
            set
            {
                //this.txtID.Text = .ToString();
                LoadDetailsForm(value);
            }
        }

        public Int32 CompanyID
        {
            get
            {
                if (this.txtCompanyID.Text == "")
                    this.txtCompanyID.Text = "0";
                return Convert.ToInt32(this.txtCompanyID.Text);
            }
            set
            {
                this.txtCompanyID.Text = value.ToString();
            }
        }

        public string PersonSurname
        {
            get { return this.txtSurname.Text; }
        }

        public event System.EventHandler SaveClicked;
        private void PersonFormControl_SaveClicked(object sender, EventArgs e) { }
        public delegate void SaveClickEventHandler(object sender, EventArgs e);

        public event System.EventHandler ListsBuilt;
        private void PersonFormControl_ListsBuilt(object sender, EventArgs e) { }
        public delegate void ListsBuiltEventHandler(object sender, EventArgs e);

        public event System.EventHandler MembershipChanged;
        private void PersonFormControl_MembershipChanged(object sender, EventArgs e) { }
        public delegate void MembershipChangedEventHandler(object sender, EventArgs e);

        public event System.EventHandler LoadDupClicked;
        private void PersonFormControl_LoadDupClicked(object sender, EventArgs e) { }
        public delegate void LoadDupClickEventHandler(object sender, EventArgs e);

        public event System.EventHandler SomethingClicked;
        private void PersonFormControl_SomethingClicked(object sender, EventArgs e) { }
        public delegate void SomethingClickedEventHandler(object sender, EventArgs e);

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Functions.dropDownListPopulate(this.ddlGenderID, sqlDB.getDataSet("SELECT ID,Description FROM Gender order by Description"), "ID", "Description");
                Functions.dropDownListPopulate(this.ddlEthnicOriginID, sqlDB.getDataSet("SELECT ID,Description FROM EthnicOrigin order by Description"), "ID", "Description");
                this.TabContainer1.ActiveTabIndex = 0;
            }
        }
        public void EnableControls()
        {
            Functions.enableChildControls(this.pnlDetails);
            this.txtUserNameModifiedBy.Enabled = false;
            this.txtRecordDate.Enabled = false;
            this.trID.Visible = true;// (txtID.Text != "");
            this.TabPanel2.Visible = (txtID.Text != "");
            this.txtID.Enabled = false;
            if (this.EndUserMode)
                Functions.disableChildControls(this.pnlCompanies);
        }
        public void setForAdding()
        {
            Functions.clearChildcontrols(this.pnlDetails);
            this.hypContactRecs.Visible = false;
            this.trID.Visible = true;
            EnableControls();
        }

        private void LoadDetailsForm(Int32 ID)
        {
            Person person = new Person();
            person.load(ID);

            Functions.populateFormControlsFromDataTableFields(person, this.pnlDetails);
            this.hypContactRecs.Visible = true;
            this.hypContactRecs.NavigateUrl = "ContactRecordsForm.aspx?PersonID=" + this.txtID.Text;
            EnableControls();
            buildListBox1();
            loadUserRegTab(ID);

        }

        private void loadUserRegTab(int personID)
        {
            //User user = new User(); user.load(Convert.ToInt32(Session["UserID"]));
            //UserRegistration userRegistration = new UserRegistration();
            //userRegistration.loadByPersonID(personID);
            ////Request.QueryString["Mode"].ToString().ToLower() == "approval"
            //this.txtConsultantName.Enabled = false;
            //this.btnAssign.Visible = false;
            //this.btnApprove.Visible = false;
            //if (user.CanDo("User reg re-assign consultant") && Functions.IsNull(userRegistration.Fields["ConsultantIDAssigned"]))
            //{
            //    this.txtConsultantName.Enabled = true; this.txtConsultantName.ReadOnly = false;
            //    this.btnAssign.Visible = true;
            //}
            //else if (userRegistration.Fields["ApprovedDate"] == DBNull.Value && user.CanDo("Approve user registration"))
            //{
            //    this.btnApprove.Visible = true;
            //}
            //Functions.populateFormControlsFromDataTableFields(userRegistration, this.tblUserReg);
            //this.txtProvince.Text = userRegistration.Province;
            //if (userRegistration.Fields["ConsultantIDAssigned"] != DBNull.Value)
            //{
            //    Consultant consultant = new Consultant(); consultant.load(Convert.ToInt32(userRegistration.Fields["ConsultantIDAssigned"]).ToString());
            //    this.txtConsultantName.Text = consultant.FullName;
            //    hypMailtoConsultant.Text = "Email " + consultant.FullName; 
            //    hypMailtoConsultant.Visible = true; 
            //    hypMailtoConsultant.NavigateUrl = "mailto:" + consultant.Email;
            //}
            //this.WorkItemsFormControl1.loadForm("UserRegistration", "ID", Convert.ToInt32(userRegistration.KeyValue));
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            Person person = new Person(); person.load(this.PersonID);
            //person.approveUserRegistration(Convert.ToInt32(Session["UserID"]), Request.ServerVariables["SERVER_NAME"], Request.ServerVariables["SERVER_PORT"]);
            //this.btnApprove.Visible = false;
            //this.LabelWithTimedMsg1.ShowStatusMessage("Successfully approved");
            loadUserRegTab(this.PersonID);

        }
        protected void lnkLoadDup_Click(object sender, EventArgs e)
        {
            if (this.lnkLoadDup.Attributes["DupID"] != "")
            {
                LoadDetailsForm(Convert.ToInt32(this.lnkLoadDup.Attributes["DupID"]));
                this.lnkLoadDup.Visible = false;
            }

            if (this.LoadDupClicked != null)
                this.LoadDupClicked(sender, e);
        }

        private void Save()
        {
            this.lnkLoadDup.Attributes["DupID"] = "";
            this.lnkLoadDup.Visible = false;
            Persons persons = new Persons();
            int dupID = persons.getDuplicatePersonID(this.txtIDNumber.Text, this.txtID.Text);
            if (dupID != 0)//Duplicate exists
            {
                this.lnkLoadDup.Attributes["DupID"] = dupID.ToString();
                this.lnkLoadDup.Visible = true;
                this.trID.Visible = true;
                // SuccessfullySaved = false;
            }
            else //Save
            {
                Person person = new Person();

                if (this.txtID.Text == "") { person.setForAdd(); } else { person.load(this.txtID.Text); }
                person.Fields["Surname"] = this.txtSurname.Text;
                person.Fields["FirstName"] = this.txtFirstName.Text;
                person.Fields["IDNumber"] = this.txtIDNumber.Text;
                person.Fields["PostalAddress"] = this.txtPostalAddress.Text;
                person.Fields["ResidentialAddress"] = this.txtResidentialAddress.Text;
                person.Fields["Office"] = this.txtOffice.Text;
                person.Fields["Department"] = this.txtDepartment.Text;
                person.Fields["PositionHeld"] = this.txtPositionHeld.Text;
                person.Fields["Email"] = this.txtEmail.Text;
                person.Fields["TelWork"] = this.txtTelWork.Text;
                person.Fields["TelCell"] = this.txtTelCell.Text;
                person.Fields["Fax"] = this.txtFax.Text;
                person.Fields["EthnicOriginID"] = this.ddlEthnicOriginID.SelectedValue;
                person.Fields["GenderID"] = this.ddlGenderID.SelectedValue;
                person.Fields["IsHistoricallyDisadvantaged"] = this.chkIsHistoricallyDisadvantaged.Checked;
                person.Fields["IsDisabled"] = this.chkIsDisabled.Checked;
                person.Fields["DateOfBirth"] = this.calDateOfBirth.Text;
                
                

                person.UserIDModifiedBy = Convert.ToInt32(Session["UserID"]);
                person.updateWithUserIDDate(); //Updates RecordDate
                this.PersonID = Convert.ToInt32(person.KeyValue);
                if (this.CompanyID != 0)
                {
                    LatestCompanyPersonID = person.AddToCompany(Convert.ToInt32(CompanyID)); //person.AddToCompany(CompanyID);
                }
                person = null;
                SuccessfullySaved = true;
                lblSaveMessage.ShowStatusMessage("Successfully saved");
            }
        }

        public void btnSave_Click(object sender, EventArgs e)
        {
            SuccessfullySaved = false;
            this.lblIDNumInvalid.Visible = false; this.lblIDNumInvalid.Text = "";
            SAIdentityNumber sAIdentityNumber = new SAIdentityNumber(this.txtIDNumber.Text);
            if (!sAIdentityNumber.IsValid)
            {
                this.lblIDNumInvalid.Visible = true;
                this.lblIDNumInvalid.Text = "Please enter a valid S.A. ID No.";
            }
            else
            {
                if (Convert.ToDateTime(this.calDateOfBirth.Text) != sAIdentityNumber.DateOfBirth)
                {
                    this.lblIDNumInvalid.Visible = true;
                    this.lblIDNumInvalid.Text = "ID No. and date of birth must match";
                }
                else
                {
                    Save();

                }
            }
            if (this.SaveClicked != null)
                this.SaveClicked(sender, e);
        }

        protected void btnRemove_Click(object sender, EventArgs e)
        {
            Person person = new Person();
            person.load(this.PersonID);

            foreach (ListItem item in this.lstYes.Items)
            {
                if (item.Selected)
                {
                    person.RemoveFromCompany(Convert.ToInt32(item.Value));
                }
            }
            person = null;
            buildListBox1();
            //buildListBox2();
            if (this.ListsBuilt != null)
                this.ListsBuilt(sender, e);
            if (this.MembershipChanged != null)
                this.MembershipChanged(sender, e);
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Person person = new Person();
            person.load(this.PersonID);

            foreach (ListItem item in this.lstNo.Items)
            {
                if (item.Selected)
                {
                    LatestCompanyPersonID = person.AddToCompany(Convert.ToInt32(item.Value));
                }
            }
            person = null;
            buildListBox1();
            buildListBox2();
            if (this.ListsBuilt != null)
                this.ListsBuilt(sender, e);
            if (this.MembershipChanged != null)
                this.MembershipChanged(sender, e);

        }

        private void buildListBox1()
        {
            string sql;
            sql = "SELECT c.ID, c.CompanyName FROM Company c " +
                "INNER JOIN CompanyPerson cp ON c.ID = cp.CompanyID and cp.PersonID = " + PersonID.ToString() +
                " order by c.CompanyName ";
            Functions.listBoxPopulate(this.lstYes, sql, "ID", "CompanyName");
        }

        private void buildListBox2()
        {
            string sql;
            sql = "SELECT top 50 c.ID, c.CompanyName FROM Company c " +
                "left JOIN CompanyPerson cp ON c.ID = cp.CompanyID and cp.PersonID = " + PersonID.ToString() +
                " where cp.ID is null ";
            this.txtCompanyNameSearch.Text = this.txtCompanyNameSearch.Text.Trim();
            if (this.txtCompanyNameSearch.Text != "")
            {
                sql += " and c.CompanyName like '" + this.txtCompanyNameSearch.Text + "%' ";
            }
            sql += "order by c.CompanyName ";
            Functions.listBoxPopulate(this.lstNo, sql, "ID", "CompanyName");
        }

        protected void btnGo_Click(object sender, EventArgs e)
        {
            buildListBox2();
            if (this.ListsBuilt != null)
                this.ListsBuilt(sender, e);
        }

        protected void btnAssign_Click(object sender, EventArgs e)
        {
            //User user = new User(); user.load(Convert.ToInt32(Session["UserID"]));
            //UserRegistration userRegistration = new UserRegistration();
            //userRegistration.loadByPersonID(PersonID);

            //StaffMembers staffMembers = new StaffMembers();
            //int ConsultantID = staffMembers.GetConsultantIDFromName(this.txtConsultantName.Text);
            //if (ConsultantID == -1) //No company found
            //{
            //    // this.IsValid = false;
            //    this.reqConsultant.ErrorMessage = "* This consultant does not exist";
            //    this.reqConsultant.Enabled = true; this.reqConsultant.Visible = true;
            //    if (SomethingClicked != null)
            //        SomethingClicked(sender, e);
            //}
            //else
            //    userRegistration.Fields["ConsultantIDAssigned"] = ConsultantID;

            //userRegistration.UserIDModifiedBy = Convert.ToInt32(Session["UserID"]);
            //userRegistration.updateWithUserIDDate("UserReg:Assign User registration to BDC");
            //loadUserRegTab(PersonID);
        }
    }
}